import { Input, Tree } from 'antd'
import { useEffect, useState } from 'react'
import { findChildren } from '@/api/project-flow.js'
import { getTreeIdList } from '../type-tree/index.jsx'
import { filterTreeData } from '@/utils/index.js'

const fieldNames = {
  title: 'name',
  key: 'id',
  children: 'children'
}

const ChildrenTree = (props) => {
  const { node, changeNodeData, canvasType } = props

  const [treeData, setTreeData] = useState([])
  const [keyword, setKeyword] = useState('')
  const [filterData, setFilterData] = useState([])

  const [ expandedKeys, setExpandedKeys ] = useState([])

  const onKeywordChagne = (e) => {
    setKeyword(e.target.value)
  }

  useEffect(() => {
    if (node && node.id && canvasType) {
      findChildren({
        nodeId: node.id,
        type: canvasType,
      }).then((res) => {
        setTreeData(res.data)
      })
    } else {
      setTreeData([])
    }
  }, [node, canvasType])

  useEffect(() => {
    if (treeData && keyword) {
      let searchData = filterTreeData(treeData, (item) => {
        return item.name.indexOf(keyword) > -1
      })
      setFilterData(searchData)
    } else {
      setFilterData(treeData)
    }
  }, [treeData, keyword])

  useEffect(() => {
    setExpandedKeys(getTreeIdList(filterData))
  }, [filterData])

  const onSelect = (selectedKeys, {selected, selectedNodes, node, event}) => {
    if (selected) {
      changeNodeData({
        canvasType: canvasType,
        typeCode: node.node_type,
        nodeId: node.id,
        nodeName: node.name
      })
    }
  }

  const onExpand = (expandedKeys) => {
    setExpandedKeys(expandedKeys)
  }

  return (
    <div className="top-bottom-layout">
      <Input
        value={keyword}
        onChange={onKeywordChagne}
        placeholder={`请输入`}
        style={{ marginBottom: '8px' }}
        autoComplete='off'
      />
      <div className="flex-1">
        <Tree
          expandedKeys={expandedKeys}
          onExpand={onExpand}
          fieldNames={fieldNames}
          blockNode={true}
          treeData={filterData}
          onSelect={onSelect}
          defaultExpandAll
        />
      </div>
    </div>
  )
}

export default ChildrenTree
